package com.taotao.search.service;

import com.taotao.common.pojo.SearchItem;
import com.taotao.common.pojo.SearchResult;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.search.dao.SearchDao;
import com.taotao.search.mapper.SearchItemMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.impl.HttpSolrClient;
import org.apache.solr.common.SolrInputDocument;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private SearchItemMapper searchItemMapper;

    @Autowired
    private HttpSolrClient httpSolrClient;

    @Autowired
    private SearchDao searchDao;

    @Override
    public TaotaoResult importAllSearchItems() throws Exception {
        //查询商品列表
        List<SearchItem> searchItemList = searchItemMapper.getSearchItemList();
        //通过solrj写入到索引库
        for (SearchItem searchItem : searchItemList) {
            SolrInputDocument document = new SolrInputDocument();
            document.addField("id", searchItem.getId().toString());//这里是字符串需要转换
            document.addField("item_title", searchItem.getTitle());
            document.addField("item_sell_point", searchItem.getSell_point());
            document.addField("item_price", searchItem.getPrice());
            document.addField("item_image", searchItem.getImage());
            document.addField("item_category_name", searchItem.getCategory_name());
            document.addField("item_desc", searchItem.getItem_desc());
            httpSolrClient.add(document);
        }

        //提交
        httpSolrClient.commit();
        return TaotaoResult.ok();
    }

    @Override
    public SearchResult search(String queryString, Integer page, Integer rows) throws Exception {
        //1.创建solr对象-->在service中创建查询对象直接传递给dao执行查询
        SolrQuery solrQuery = new SolrQuery();
        if (StringUtils.isNotBlank(queryString)) {
            solrQuery.setQuery(queryString);
        } else {
            solrQuery.setQuery("*:*");
        }

        // 设置过滤条件 分页
        if (page == null) page = 1;
        if (rows == null) rows = 60;
        solrQuery.setStart(page);
        solrQuery.setRows(rows);
        //设置默认搜索域
        solrQuery.set("df", "item_keywords");
        //设置高亮
        solrQuery.setHighlight(true);
        solrQuery.setHighlightSimplePre("<em style=\"color:red\">");
        solrQuery.setHighlightSimplePost("</em>");
        solrQuery.addHighlightField("item_title");//设置高亮显示的域

        SearchResult search = searchDao.search(solrQuery);
        //设置总页数
        long pageCount = 0l;
        pageCount = search.getRecordCount() / rows;
        if (search.getRecordCount() % rows > 0) {
            pageCount++;
        }
        search.setPageCount(pageCount);
        return search;
    }
}
